﻿using System;

namespace Crypt.Common
{
    /// <summary>
	/// xxtea 的 加密算法。
	/// </summary>
    public class XXTea
    {
        /// <summary>
        /// 默认key
        /// </summary>
        // private static string DEFAULT_KEY = "1234567890abcdef";

        /// 获取XXTea16位密钥
        /// </summary>
        /// <param name="key">XXTea密钥字符串</param>
        /// <returns>XXTea16位密钥</returns>
        private static byte[] CheckXXTeaKey(string inKey)
        {
            if (string.IsNullOrEmpty(inKey))
            {
                throw new ArgumentNullException("key", "XXTea密钥不能为空");
            }
            if (inKey.Length < 16)
            {
                // 不足16补全
                inKey = inKey.PadRight(16, '0');
            }
            if (inKey.Length > 16)
            {
                inKey = inKey.Substring(0, 16);
            }
            return System.Text.Encoding.UTF8.GetBytes(inKey);
        }


        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="Data">字节数组</param>
        /// <param name="Key">加密秘钥</param>
        /// <returns></returns>
        private static Byte[] Encrypt(Byte[] Data, Byte[] Key)
        {
            if (Data.Length == 0)
            {
                return Data;
            }
            // 1:private static UInt32[] ToUInt32Array(Byte[] Data, Boolean IncludeLength)  xxtea
            // 2:private static UInt32[] Encrypt(UInt32[] v, UInt32[] k)                    xxtea
            // 3:private static Byte[] ToByteArray(UInt32[] Data, Boolean IncludeLength)    xxtea
            return ToByteArray(Encrypt(ToUInt32Array(Data, true), ToUInt32Array(Key, false)), false);
        }


        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="Data">字节数组</param>
        /// <param name="Key">加密秘钥</param>
        /// <returns></returns>
        private static Byte[] Decrypt(Byte[] Data, Byte[] Key)
        {
            if (Data.Length == 0)
            {
                return Data;
            }
            // 1:private static UInt32[] ToUInt32Array(Byte[] Data, Boolean IncludeLength)  xxtea
            // 2:private static UInt32[] Decrypt(UInt32[] v, UInt32[] k)                    xxtea
            // 3:private static Byte[] ToByteArray(UInt32[] Data, Boolean IncludeLength)    xxtea
            return ToByteArray(Decrypt(ToUInt32Array(Data, false), ToUInt32Array(Key, false)), true);
        }


        private static UInt32[] Encrypt(UInt32[] v, UInt32[] k)
        {
            Int32 n = v.Length - 1;
            if (n < 1)
            {
                return v;
            }
            if (k.Length < 4)
            {
                UInt32[] Key = new UInt32[4];
                k.CopyTo(Key, 0);
                k = Key;
            }
            UInt32 z = v[n], y = v[0], delta = 0x9E3779B9, sum = 0, e;
            Int32 p, q = 6 + 52 / (n + 1);
            while (q-- > 0)
            {
                sum = unchecked(sum + delta);
                e = sum >> 2 & 3;
                for (p = 0; p < n; p++)
                {
                    y = v[p + 1];
                    z = unchecked(v[p] += (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z));
                }
                y = v[0];
                z = unchecked(v[n] += (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z));
            }
            return v;
        }


        private static UInt32[] Decrypt(UInt32[] v, UInt32[] k)
        {
            Int32 n = v.Length - 1;
            if (n < 1)
            {
                return v;
            }
            if (k.Length < 4)
            {
                UInt32[] Key = new UInt32[4];
                k.CopyTo(Key, 0);
                k = Key;
            }
            UInt32 z = v[n], y = v[0], delta = 0x9E3779B9, sum, e;
            Int32 p, q = 6 + 52 / (n + 1);
            sum = unchecked((UInt32)(q * delta));
            while (sum != 0)
            {
                e = sum >> 2 & 3;
                for (p = n; p > 0; p--)
                {
                    z = v[p - 1];
                    y = unchecked(v[p] -= (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z));
                }
                z = v[n];
                y = unchecked(v[0] -= (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z));
                sum = unchecked(sum - delta);
            }
            return v;
        }


        private static UInt32[] ToUInt32Array(Byte[] Data, Boolean IncludeLength)
        {
            Int32 n = (((Data.Length & 3) == 0) ? (Data.Length >> 2) : ((Data.Length >> 2) + 1));
            UInt32[] Result;
            if (IncludeLength)
            {
                Result = new UInt32[n + 1];
                Result[n] = (UInt32)Data.Length;
            }
            else
            {
                Result = new UInt32[n];
            }
            n = Data.Length;
            for (Int32 i = 0; i < n; i++)
            {
                Result[i >> 2] |= (UInt32)Data[i] << ((i & 3) << 3);
            }
            return Result;
        }


        private static Byte[] ToByteArray(UInt32[] Data, Boolean IncludeLength)
        {
            Int32 n;
            if (IncludeLength)
            {
                n = (Int32)Data[Data.Length - 1];
            }
            else
            {
                n = Data.Length << 2;
            }
            Byte[] Result = new Byte[n];
            for (Int32 i = 0; i < n; i++)
            {
                Result[i] = (Byte)(Data[i >> 2] >> ((i & 3) << 3));
            }
            return Result;
        }


        /// <summary>
        /// 使用默认key加密字符串
        /// </summary>
        /// <param name="inStr">字符串</param>
        /// <returns></returns>
		public static string Encrypt(string inStr)
        {
            return Encrypt(inStr, string.Empty);
        }


        /// <summary>
        /// 使用指定key加密字符串
        /// </summary>
        /// <param name="inStr">字符串</param>
        /// <param name="inKey">加密秘钥</param>
        /// <returns></returns>
        public static string Encrypt(string inStr, string inKey)
        {
            byte[] inKeyArray = CheckXXTeaKey(inKey);
            Byte[] data = Encrypt(System.Text.Encoding.UTF8.GetBytes(inStr), inKey);
            return System.Convert.ToBase64String(data);

        }


        /// <summary>
        /// 使用默认key解密字符串
        /// </summary>
        /// <param name="inStr">字符串</param>
        /// <returns></returns>
		public static string Decrypt(string inStr)
        {
            return Decrypt(inStr, string.Empty);
        }


        /// <summary>
        /// 使用指定key解密字符串
        /// </summary>
        /// <param name="inStr">字符串</param>
        /// <param name="inKey">加密秘钥</param>
        /// <returns></returns>
        public static string Decrypt(string inStr, string inKey)
        {
            byte[] inKeyArray = CheckXXTeaKey(inKey);
            return System.Text.Encoding.UTF8.GetString(Decrypt(System.Convert.FromBase64String(inStr), inKeyArray));
        }


        /// <summary>
        /// 使用默认key加密数据
        /// </summary>
        /// <param name="inBuffer">字节数组</param>
        /// <returns></returns>
        public static byte[] Encrypt(byte[] inBuffer)
        {
            return Encrypt(inBuffer, string.Empty);
        }


        /// <summary>
        /// 使用指定key加密数据
        /// </summary>
        /// <param name="inBuffer">字节数组</param>
        /// <param name="inKey">加密秘钥</param>
        /// <returns></returns>
        public static byte[] Encrypt(byte[] inBuffer, string inKey)
        {
            byte[] inKeyArray = CheckXXTeaKey(inKey);
            return Encrypt(inBuffer, inKeyArray);
        }


        /// <summary>
        /// 使用默认key解密数据
        /// </summary>
        /// <param name="inBuffer">字节数组</param>
        /// <returns></returns>
        public static byte[] Decrypt(byte[] inBuffer)
        {
            return Decrypt(inBuffer, string.Empty);
        }


        /// <summary>
        /// 使用指定key解密数据
        /// </summary>
        /// <param name="inBuffer">字节数组</param>
        /// <param name="inKey">加密秘钥</param>
        /// <returns></returns>
        public static byte[] Decrypt(byte[] inBuffer, string inKey)
        {
            byte[] inKeyArray = CheckXXTeaKey(inKey);
            return Decrypt(inBuffer, inKeyArray);
        }

    }
}
